package A003_NagrajObraz;



import java.awt.AWTException;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Label;
import java.awt.MouseInfo;
import java.awt.PointerInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
import org.jnativehook.mouse.NativeMouseWheelEvent;
import org.jnativehook.mouse.NativeMouseWheelListener;

import A003_NagrajObraz.OsCheck.OSType;

import javax.swing.ImageIcon;

import java.util.Locale;
import java.awt.BorderLayout;


public class NAGRYWARKA_OBSZAROW_tm  
			implements  ActionListener, ItemListener, NativeKeyListener, 
							NativeMouseInputListener, NativeMouseWheelListener, WindowListener {
		
	private static final long serialVersionUID = 1L;
	
	public JDialog dialog;
	private Frame owner;
	private LinkedList<BufferedImage> iListaObrazow = null;
	private LinkedList<BufferedImage>iListaPosortowana = null;
	private  LinkedList<iClassBuf> iclassbuf;
	//private LinkedList<BufferedImage> iListaPosortowana = null;
	private String iPathDefoult = "";
	JFileChooser chooser;
	

		
	private JSpinner iCzasProbki;
	int iczasprobki = 20;
	

	private JPanel iRamka_obraz;
	private JPanel iObraz;
	private JLayeredPane panel;
	private JPanel iP_Obraz;
	private JPanel panel_1;
	
	private JButton buttonStartStop;
	private boolean GotowoscDoNagrywania=false;
	private boolean NAGRYWAM=false;
	private JButton btnPLAY;
	private JButton btnSTOP;
	private JButton btnReset;
	private JButton btnZapisz_1;
	
	private JPanel iParm1; //parametry szerokos pobieranego obrazka
	
	private JSpinner iWysokoscOb;
	private JSpinner iSzerokoscOb;
	private Robot rob;
	private BufferedImage iBuf; // zrzut spod kursorap
	private Image scaledImage;
	private Timer timer; //czestotliwosc probek
	private Path path;
	
	
	public JTextArea log;

	private Component horizontalStrut_1;

	public NAGRYWARKA_OBSZAROW_tm() {
		iListaObrazow = new LinkedList<BufferedImage>();
		iListaPosortowana = new LinkedList<BufferedImage>();
				
		/*try {
			GlobalScreen.registerNativeHook();
		} catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
            System.exit(1);
		}*/
		
		System.out.println("Hook state: "+ GlobalScreen.isNativeHookRegistered());
		GlobalScreen.getInstance().addNativeKeyListener(this);
		
		
		if (OSType.MacOS == OsCheck.getOperatingSystemType()){
			iPathDefoult = "002-DoFi/SET/MAC/SZUKANE/";
			System.out.println("ścieżka " + iPathDefoult);

		} else if (OSType.Windows == OsCheck.getOperatingSystemType()) {
			iPathDefoult = "002-DoFi/SET/PC/SZUKANE/";
		}

		
		try {
			rob = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}

		try {
			String path = new java.io.File("..").getCanonicalPath();
				System.out.println("PATH \n" + path);
			//this.buf = ImageIO.read(new File(path+"/002-DoFi/src/NagrywarkaObrazkow/iKatObraz/centerConf.bmp"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize(Container parent, String title) {
		
		owner = null;
		if (parent instanceof Frame) owner = (Frame) parent;
		else owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
		
		if (dialog == null || dialog.getOwner()!=owner){
			dialog = new JDialog(owner, true);
		}
		
		dialog = new JDialog();
		dialog.getContentPane().setLocale(new Locale("pl"));
		dialog.setAlwaysOnTop(true);

		dialog.setTitle(title);
		dialog.setBounds(100, 100, 256, 552);
		dialog.getContentPane().setLayout(null);

		iRamka_obraz = new JPanel();
		iRamka_obraz.setBounds(5, 6, 156, 156);
		iRamka_obraz.setBorder(new MatteBorder(3, 3, 3, 3, (Color) new Color(0, 0, 0)));
		iRamka_obraz.setBackground(Color.DARK_GRAY);
		iRamka_obraz.setLayout(null);
		dialog.getContentPane().add(iRamka_obraz);
		
		dialog.addWindowListener(new WindowListener() {
			
			@Override
			public void windowOpened(WindowEvent e) {	}
			
			@Override
			public void windowIconified(WindowEvent e) {	}
			
			@Override
			public void windowDeiconified(WindowEvent e) {	}
			
			@Override
			public void windowDeactivated(WindowEvent e) {	}
			
			@Override
			public void windowClosing(WindowEvent e) {
				System.out.println("close");
				System.exit(0);
				SwingUtilities.getWindowAncestor(dialog).dispose();
			}
			
			@Override
			public void windowClosed(WindowEvent e) {	}
			
			@Override
			public void windowActivated(WindowEvent e) {	}
		});
		
		iP_Obraz = new iObraz();
		iRamka_obraz.add(iP_Obraz);

		panel_1 = new JPanel();
		panel_1.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				System.out.println(e.getKeyChar());

			}
		});
		
		iParm1 = new JPanel();
		iParm1.setBounds(5, 174, 156, 87);
		dialog.getContentPane().add(iParm1);
		iParm1.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		iParm1.setLayout(new GridLayout(0, 3, 0, 0));
		
		
		iSzerokoscOb = new JSpinner();
		iSzerokoscOb.setToolTipText("Szeroko\u015B\u0107 pr\u00F3bki 1-301px");
		iSzerokoscOb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				iWysokoscOb.setValue((long) iSzerokoscOb.getValue());
			}
		});
		
		horizontalStrut_1 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_1);
		iSzerokoscOb.setModel(new SpinnerNumberModel(new Long(7), new Long(1), new Long(301), new Long(10)));
		iParm1.add(iSzerokoscOb);
		
		
		iWysokoscOb = new JSpinner();
		iWysokoscOb.setToolTipText("Wysoko\u015B\u0107 pr\u00F3bki 1-301px");
		iWysokoscOb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				iSzerokoscOb.setValue((long) iWysokoscOb.getValue());
			}
		});
		
		JLabel lblSzer_1 = new JLabel("szer.");
		lblSzer_1.setHorizontalAlignment(SwingConstants.CENTER);
		lblSzer_1.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblSzer_1);
		
		Component horizontalStrut_2 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_2);
		iWysokoscOb.setModel(new SpinnerNumberModel(new Long(7), new Long(1), new Long(301), new Long(10)));
		iWysokoscOb.setFont(new Font("Tahoma", Font.BOLD, 11));
		iParm1.add(iWysokoscOb);
		
		JLabel lblWys = new JLabel("wys.");
		lblWys.setHorizontalAlignment(SwingConstants.CENTER);
		lblWys.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblWys);
		
		Component horizontalStrut_3 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_3);
		
		iCzasProbki = new JSpinner();
		iCzasProbki.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				iczasprobki = (int)iCzasProbki.getValue();
				timer.setDelay(iczasprobki);
			}
		});
		iCzasProbki.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), new Integer(500), new Integer(1)));
		iCzasProbki.setToolTipText("Szybko\u015B\u0107 probki obrazu 10-500ms");
		iParm1.add(iCzasProbki);
		
		JLabel lblms = new JLabel("ms");
		lblms.setHorizontalAlignment(SwingConstants.CENTER);
		lblms.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblms);
		panel_1.setBounds(5, 262, 156, 95);
		dialog.getContentPane().add(panel_1);
		panel_1.setLayout(new GridLayout(0, 2, 0, 0));
		
		
		buttonStartStop = new JButton("");
		buttonStartStop.setMnemonic(KeyEvent.VK_KP_LEFT);
		final ImageIcon ikona1 = 
				new ImageIcon(NAGRYWARKA_OBSZAROW_tm.class.getResource
						("/A003_NagrajObraz/Images/play20x20.png"));
		final ImageIcon ikona2 = 
				new ImageIcon(NAGRYWARKA_OBSZAROW_tm.class.getResource
						("/A003_NagrajObraz/Images/stop20x20.png"));
		if (GotowoscDoNagrywania == false)
			{buttonStartStop.setIcon(ikona1);}
		else if (GotowoscDoNagrywania == true)
			{buttonStartStop.setIcon(ikona2);}
		dialog.getRootPane().setDefaultButton(buttonStartStop);
		buttonStartStop.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (GotowoscDoNagrywania == false){
					buttonStartStop.setIcon(ikona2);
					//--------------
					GotowoscDoNagrywania = true;
					btnPLAY.setEnabled(true);
				} else{ // if is true
					if (iListaObrazow.size() > 0 || iListaPosortowana.size() > 0){
						
					}
					buttonStartStop.setIcon(ikona1);
					GotowoscDoNagrywania = false;
					//--------------
					NAGRYWAM = false;
					// akcaj jesli do sotownia jest lista
					if  (NAGRYWAM == false && iListaObrazow.size()>0){
						try {
							iSortuj();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
					btnPLAY.setEnabled(false);
				}
				System.out.println("Nagrywanie - " + GotowoscDoNagrywania);
			}
		});	
		buttonStartStop.setToolTipText("Naci\u015Bnij \"ENTER\" zablokujesz ramk\u0119 podgladu");
		panel_1.add(buttonStartStop);
		
		btnPLAY = new JButton("NAGRYWAJ");
		btnPLAY.setEnabled(false);

		btnPLAY.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				if (GotowoscDoNagrywania == false){
					//JOptionPane.showMessageDialog(dialog, "Nie jest zastopowana klatka\n NACISNIJ KLAWIS <S>");
					return;
				}
				NAGRYWAM = true;
				btnPLAY.setEnabled(false);
			}
		});
		btnPLAY.setToolTipText("Naci\u015Bnij \"S\" odblokujesz ramk\u0119 podgladu");
		panel_1.add(btnPLAY);
		
		btnReset = new JButton("RESET");
		btnReset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (GotowoscDoNagrywania == false && NAGRYWAM ==false){
					Reset();
				}
			}

			private void iCel() {
				Dialog dial = null;
				
				if(dial!=null)System.out.println("jest okno");
				else 
					dial = new Dialog(dialog, "test");
				
				dial.setVisible(true);
				dial.setLayout(new FlowLayout());
				dial.setSize(200, 200);
				dial.setAlwaysOnTop(true);
				dial.add(new Label ("Nacisnij punkt szukania na obrazku"));
				dial.add(new Button("yes"));
			}
		});
		panel_1.add(btnReset);
		
		btnZapisz_1 = new JButton("zapisz");
		btnZapisz_1.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent arg0) {
				try {
					iZapisz();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		panel_1.add(btnZapisz_1);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(5, 360, 245, 165);
		panel_2.setLayout(new GridLayout(0, 1, 0, 0));
		dialog.getContentPane().add(panel_2);
		
		log = new JTextArea();
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
		panel_2.add(log);
        JScrollPane logScrollPane = new JScrollPane(log);
        panel_2.add(logScrollPane);
        
        panel_info = new JPanel();
        panel_info.setBounds(166, 6, 84, 53);
        dialog.getContentPane().add(panel_info);
        panel_info.setLayout(new BorderLayout(0, 0));
        
        lblPOSort = new JLabel("0000");
        lblPOSort.setFont(new Font("Lucida Grande", Font.PLAIN, 28));
        lblPOSort.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblPOSort);
        
        lblPrzedSort = new JLabel("0000");
        lblPrzedSort.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblPrzedSort, BorderLayout.NORTH);

				
		timer = new Timer(iczasprobki, action);
		timer.start();
		
		dialog.setVisible(true);

	}
	int a = 0, b=0, sz=0, w=0; String text;
	private ActionListener action = new ActionListener() {
		public void actionPerformed(ActionEvent ae) {
			//System.out.println("starat");
			if(!GotowoscDoNagrywania){
				a = igetCurrentPosX();
				b = igetCurrentPosY();
			}
			if(!NAGRYWAM){
				sz = (int)(long)iSzerokoscOb.getValue();
				w  = (int)(long)iWysokoscOb.getValue();
			}
			iBuf = rob.createScreenCapture(new Rectangle (a-sz/2, b-w/2, sz, w));
			if (NAGRYWAM == true && iListaObrazow != null) {
				iListaObrazow.add(iBuf);
			}
			lblPrzedSort.setText(""+iListaObrazow.size());

			if (iListaPosortowana == null) text = "00pu"; else text = ""+iListaPosortowana.size();
			lblPOSort.setText(text);
			
			panel_info.repaint();
			iRamka_obraz.repaint();
		}
	};
	//============================================================================
	private int igetCurrentPosX(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.print("POZYCJA MOUSA X: " + pointer.getLocation().x + " ");
		return pointer.getLocation().x;
	}
	private int igetCurrentPosY(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.println("POZYCJA MOUSA Y: " + pointer.getLocation().y);
		return pointer.getLocation().y;
	}
	

	protected void Reset() {
		iListaObrazow.clear();
		iListaPosortowana.clear();;	
	}
	private class iClassBuf {
		// clasa z informacja o zrzucie jego wielkosci i zawartosci
		int iBuf[];
		BufferedImage iBuffImg;
		int iSzerokosc;
		int iWysokosc;
		String iNazwa;
		
		public iClassBuf(int buff[], int szerokosc, int wysokosc, String nazwa){
			iBuf = buff;
			iSzerokosc = szerokosc;
			iWysokosc = wysokosc;
			iNazwa = nazwa;
			//if (iBuf.length>0 || iBuf != null){
				//convert conv = new convert();
				//conv.run();
			//}
		}
		class convert implements Runnable{

			@Override
			public void run() {
				
			}
		}
	}

	class iObraz extends JPanel {
		//private Image img = null;
		int wFrameObraz;
		int hFrameObraz;
		
		public iObraz() {
			super();
	
			setBackground(Color.gray);
			setBounds(new Rectangle(10, 11, 136, 134));
			setBorder(BorderFactory.createLineBorder(Color.black));
			setLayout(new FlowLayout(FlowLayout.CENTER)); 
		}
		
		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
	
			wFrameObraz = iP_Obraz.getSize().width;
			hFrameObraz = iP_Obraz.getSize().height;
			if ( iBuf !=  null ){
				scaledImage = (iBuf.getScaledInstance(wFrameObraz, wFrameObraz, (Image.SCALE_AREA_AVERAGING)));
				g.drawImage(scaledImage, 0, 0, null);
			}
		}
	}
			
		@Override
		public void windowOpened(WindowEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void windowClosing(WindowEvent e) {
			System.out.println("zmaykasz okno)");		
		}
		
		@Override
		public void windowClosed(WindowEvent e) {
			//Clean up the native hook.
			GlobalScreen.unregisterNativeHook();
			System.runFinalization();
			System.exit(0);
		}
		
		@Override
		public void windowIconified(WindowEvent e) {	}
		
		@Override
		public void windowDeiconified(WindowEvent e){	}
		
		@Override
		public void windowActivated(WindowEvent e) {	}
		
		@Override
		public void windowDeactivated(WindowEvent e) {	}
		
		@Override
		public void nativeKeyPressed(NativeKeyEvent arg0) {
				int a=arg0.getKeyCode();
				System.out.println("nacisniety klawisz-"+a+" "+arg0.getKeyText(a)+" "+ arg0.paramString());
				switch (a){
					case (KeyEvent.VK_MINUS):
						if(iczasprobki<=0)break; 
						iCzasProbki.setValue(iczasprobki-10);
						break;
					case (KeyEvent.VK_EQUALS):
						if(iczasprobki>0)break;
						iCzasProbki.setValue(iczasprobki+10);
						break;
					case KeyEvent.VK_ADD: 
						if ((long)iWysokoscOb.getValue()<301 && ((long)iWysokoscOb.getValue())>=12) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+2);
						if ((long)iWysokoscOb.getValue()<301 && ((long)iWysokoscOb.getValue())<12) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+2);
						break;
					case KeyEvent.VK_SUBTRACT: 
						if ((long)iWysokoscOb.getValue()> 5 && ((long)iWysokoscOb.getValue())>=12) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						if ((long)iWysokoscOb.getValue()> 5 && ((long)iWysokoscOb.getValue())< 12) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						break;
					case KeyEvent.VK_LEFT: 
						break;
					case KeyEvent.VK_RIGHT: 
						break;	
					case KeyEvent.VK_ESCAPE: 
						GlobalScreen.unregisterNativeHook();
						System.runFinalization();
						System.exit(2);
						break;
				}
		}
		
		@Override
		public void nativeKeyReleased(NativeKeyEvent arg0) {	}
		
		@Override
		public void nativeKeyTyped(NativeKeyEvent arg0) {	}
		
		@Override
		public void nativeMouseClicked(NativeMouseEvent arg0) {	}
		
		@Override
		public void nativeMousePressed(NativeMouseEvent arg0) {	}
		
		@Override
		public void nativeMouseReleased(NativeMouseEvent arg0) {	}
		
		@Override
		public void nativeMouseDragged(NativeMouseEvent arg0) {	}
		
		@Override
		public void nativeMouseMoved(NativeMouseEvent arg0){	}
		
		@Override
		public void actionPerformed(ActionEvent e) {	}
		
		@Override
		public void nativeMouseWheelMoved(NativeMouseWheelEvent arg0) {	}
		
		@Override
		public void itemStateChanged(ItemEvent e) {	}
		

		public void iLog(String log) {
			this.log.append(""+log +"\n");
		}
		
		/**
		 * Laduje do LinkedList
		 * @param buf
		 */
		public void iIN (BufferedImage buf){
			if (iListaObrazow == null) {
				iListaObrazow = new LinkedList<BufferedImage>();
			}
			iListaObrazow.add(buf);
		}
		
		/**
		 * Usuwa zbędne elmenty z tablicy
		 * @throws IOException 
		 */
		public void iSortuj() throws IOException{
			if (iListaObrazow == null || iListaObrazow.size() == 0) return;

			int iloscElementow = iListaObrazow.size();
			BufferedImage el1=null, el2=null;
			int LP = 0;
			
			for (int a = 0; a < iListaObrazow.size(); a++){
				for (int b = a+1; b < iListaObrazow.size(); b++){
					
					
					el1 = iListaObrazow.get(a);
					el2 = iListaObrazow.get(b);
					
					
					if (el1 != null && el2 != null) {
						if (el1.getWidth() != el2.getWidth() || el1.getHeight() != el2.getHeight()) {
							JOptionPane.showConfirmDialog(dialog, "OBRAZY SĄ NIE ZGONE WIELKOŚCIOWO");
							Reset();
							return;
						}
						
						if (iPorownaj(el1, el2)) {
							iListaObrazow.set(b, null); // if jest taki sam jest usuwany
							//System.out.println("NULL");
						}; 
					}				
				}
				if (el1 !=null) {
					iListaPosortowana.add(el1);
				}
			}
			//System.out.println("Lista przed sortowaniem Elementów -" + iListaObrazow.size());
			//System.out.println("Lista posortowana elementow-" + iListaPosortowana.size());
			return;
		}
		
		private JLabel lblPOSort;
		private JLabel lblPrzedSort;
		private JPanel panel_info;
		private boolean iPorownaj (BufferedImage el1, BufferedImage el2){
			int tolerancja = 5;
			int a = 0;
			for (int y = 0; y < el1.getHeight(); y++){
				for (int x = 0; x < el1.getWidth(); x++){
					a = Math.abs(el1.getRGB(x, y) - el2.getRGB(x, y));
					if (a >= tolerancja) {
						//System.out.println(" Tolerancja za wysoka wynosi " + a);
							return false;
					}
				}
			}
			return true;
		}
		
		
		public void iZapisz() throws IOException{
			
			System.out.println("Zapisuje elementow " 
					+ iListaPosortowana.size());
			
			BufferedImage buff=null;
			try{	
				buff = iListaPosortowana.getFirst();
			} catch (NoSuchElementException no){
				JOptionPane.showConfirmDialog(null, "Brak elemntów do zapisu");
			} 
			
			Iterator it = iListaPosortowana.iterator();
			BufferedImage buf = null;
			File iPathFolder = null;
			int licz = 0;
			
			JFileChooser chooser = new JFileChooser();
		    chooser.setCurrentDirectory(
		    		new java.io.File (iInitLinki.iGlobalPathSET + iInitLinki.iKatSys + "SZUKANE/"));
		      System.out.println("test1: " +iInitLinki.iGlobalPathSET + iInitLinki.iKatSys + "SZUKANE/"); 

			chooser.setFileFilter(
					new FileNameExtensionFilter("BMP", "bmp"));

			int result = chooser.showSaveDialog(null);
		    
			if (result == JFileChooser.CANCEL_OPTION){
				iListaObrazow = null;
				iListaPosortowana = null;
				return;
			}
			    
			//File file = chooser.getSelectedFile();
		    if (result == JFileChooser.APPROVE_OPTION) { 
		    	iPathFolder = chooser.getCurrentDirectory();
		      System.out.println("getCurrentDirectory(): " 
		         +  iPathFolder);
		      System.out.println("getSelectedFile() : " 
		         +  chooser.getSelectedFile());
		      }
		    else {
		      System.out.println("No Selection ");
		      }
		    
		    while (it.hasNext()){
		    	buf =  (BufferedImage) it.next();
		    	File outputfile = new File(chooser.getSelectedFile() + "_" + licz++ +".bmp");
			    ImageIO.write(buf, "bmp", outputfile);
			    
		    	iLog(""+outputfile.getAbsoluteFile()); 
		    }
		    
			iListaObrazow = iListaPosortowana;
		}
		

		/**
		 * Launch the application.
		 */
		public static void main(String[] args) {
			System.out.println("test");
				NAGRYWARKA_OBSZAROW_tm window = new NAGRYWARKA_OBSZAROW_tm();
				window.initialize(null, "NAGRYWARKA");
			System.out.println("test");

		}
}
